package com.example.gpstracking.database;

import java.util.ArrayList;

import com.example.gpstracking.object.Data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteManager {
	
	private SQLiteDatabase mDatabase;
	private MySqliteHelper mSqliteHelper;
	private Context mContext;
	
	public MySQLiteManager(Context context)
	{
		mContext = context;
		mSqliteHelper = MySqliteHelper.getInstance(context);
		mDatabase = mSqliteHelper.getWritableDatabase();
	}
	public boolean InsertData(ContentValues contentValues)
	{
		if( contentValues != null )
		{
			if(!mDatabase.isOpen())
			{
				OpenDatabase();
			}
			long check = mDatabase.insert(MySqliteHelper.NAME_TABLE, null, contentValues);
			if(check == -1)
			{
				CloseDatabase();
				return false;				
			}
			else
			{
				CloseDatabase();
				return true;
			}
		}
		return false;
	}
	public ArrayList<Data> GetAllFromCursor(Cursor cursor)
	{
		ArrayList<Data> res = new ArrayList<Data>();
		if(cursor.moveToFirst())
		{
			while (cursor.moveToNext()) {				
				String time, lat, lng;
				//
				time  =cursor.getString(cursor.getColumnIndex(MySqliteHelper.TABLE_TIME));
				lat = cursor.getString(cursor.getColumnIndex(MySqliteHelper.TABLE_LAT));
				lng = cursor.getString(cursor.getColumnIndex(MySqliteHelper.TABLE_LONG));
				//
				res.add(new Data(Long.valueOf(time), Float.valueOf(lat), Float.valueOf(lng)));
				cursor.moveToNext();
			}
			cursor.close();
			
		}
		CloseDatabase();
		return res;
	}
	public ArrayList<Data> getAllFromTable(String nameTB)
	{
		OpenDatabase();
		Cursor cursor = mDatabase.rawQuery("select * from "+ nameTB , null);
		return GetAllFromCursor(cursor);
	}
	public void clearTable(String tableName)
	{
		OpenDatabase();
		mDatabase.delete(tableName, null, null);
		CloseDatabase();
	}
	public void OpenDatabase()
	{
		if( ( mDatabase == null ) || ( !mDatabase.isOpen() ) )
		{
			mDatabase = mSqliteHelper.getWritableDatabase();	
		}
	}
	public void CloseDatabase()
	{
		if(mDatabase.isOpen())
		{
			mDatabase.close();
		}
	}
}
